<?php namespace Common\Model;
use Hdphp\Model\Model;
/**
* 分类模型
*/
class Category extends Model
{
	protected $table="Category";
	protected $validate=array(
		array('cname','required','分类名称不能为空',3,3),
        array('cname','maxlen:10','分类名称不得超过10个字符',3,3),
        array('csort','num:0,65535','分类排序必须为数字',3,3),
		);
	//添加分类
	public function store()
	{
		//自动验证
		if(!$this->create()) return false;
		//把数据添加到数据库
		return $this->add();
	}
	public function del($cid)
	{
		$pid=$this->where("cid={$cid}")->piuck('pid');
		$this->where("pid={$cid}")->save(array('pid'=>$pid));
		$this->delete($cid);
	}
	public function edit($cid)
	{
		if(!$this->create()) return false;
		$this->where("cid={$cid}")->save();
		return true;
	}
	//获得除了自身和自身的所有的子集
	public function getNoMine($cid)
	{
		$cids=$this->getSon($this->get(),$cid);
		$cids[]=$cid;
		$data=$this->where("cid not in(".implode(',',$cids).")")->get();
		return Data::tree($data,'cname');
	}
	public function getSon($data,$cid)
	{
		static $temp=array();
		foreach ($data as $v) {
			if($cid==$v['pid']){
				$temp[]=$v['cid'];
				$this->getSon($data,$v['cid']);
			}
		}
		return $temp;
	}
}
?>